package Servlet;

import Entity.Player;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * This servlet is responsible for returning the necessary user data that is used to sign users into the game.
 * @author Rodge Uy
 */
public class PlayerSigninServelet extends HttpServlet {

    String username;
    Integer levelNum;
    Integer curScore;
    Integer curPicture;

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("userName") != null && request.getParameter("passWord") != null) {
            request.setAttribute("loginInfo", getLogin(request.getParameter("userName"), request.getParameter("passWord")));

            // Now that the controller has gathered the data from the model,
            // pass the data onto the view to render it as JSON.
            HttpSession session = request.getSession(true);
            session.setAttribute("currentUser", username);
            session.setAttribute("levelNum", levelNum);
            session.setAttribute("curScore", curScore);
            session.setAttribute("picture", curPicture);
            RequestDispatcher view = request.getRequestDispatcher("/login_view.jsp");
            view.forward(request, response);
        } else if (request.getParameter("logout")!=null){
            request.getSession(false).invalidate();
        }
    }

    private List<Map<String, String>> getLogin(String userName, String passWord) {
        List<Map<String, String>> login = new ArrayList<Map<String, String>>();

        try {

            Context ctx = GetContext.getContext();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            //find player by username provided
            Query p = em.createNamedQuery("Player.findByPlayName").setParameter("playName", userName);
            List<Player> nameresults = p.getResultList();

            //username cannot be found in database, return INVALID entity
            if (nameresults.isEmpty()){
                Map<String, String> invalidEntity = new HashMap<String, String>();
                invalidEntity.put("userName", "INVALID");
                invalidEntity.put("passWord", "INVALID");
                login.add(invalidEntity);
                return login;
            }

            //Now that the player's username has been confirmed to exist, this returns an entity
            //containing the username and password.
            Query q = em.createNamedQuery("Player.findByPlayerNamePassWord").setParameter("playName", userName).setParameter("passWord", passWord);
            List<Player> results = q.getResultList();
            for (Player c : results) {
                Map<String, String> entity = new HashMap<String, String>();
                entity.put("userName", "" + c.getPlayName());
                entity.put("passWord", c.getPassWord());
                login.add(entity);
                username = c.getPlayName();
                levelNum = c.getFurthestPlayedLevel();
                curScore = c.getAccumScore();
                curPicture = c.getPicture();
            }
        }
    catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return login;
}

/**
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
    public String getServletInfo(

) {
        return "Short description";
    }// </editor-fold>
}
